const Monitor = require('../../utils/monitor.js').Monitor
const util = require('../../utils/util.js')
Page(Monitor.hookApp({
  data: {
    val: '',
    imgUrl: getApp().globalData.imgUrl,
    renmenList: [],
    hotList: [],
    searchRecord: []
  },
  clean() {
    this.setData({
      val: ''
    })
  },
  bindinput(e) {
    this.setData({
      val: e.detail.value
    })
  },
  clickHistory(e) { //历史记录
    this.setData({
      val: this.data.searchRecord[e.currentTarget.dataset.idx].value
    })
    if (this.data.isFenXiao != 'true') {
      wx.redirectTo({
        url: `../ShopList/ShopList?val=${this.data.val}&title=搜索商品`
      })
    }else{
      wx.navigateTo({
        url: `/pages/fxShopList/fxShopList?val=${this.data.val}&title=搜索分销商品`
      })
    }

  },
  jumpXiangQing(e) { //搜索框跳详情
    this.setData({
      val: this.data.hotList[e.currentTarget.dataset.idx].goods_name,
      goods_id: e.currentTarget.dataset.goods_id
    })
    this.setStorage()
    if (this.data.isFenXiao != 'true') {
      wx.redirectTo({
        url: `../ShopList/ShopList?val=${this.data.val}&title=搜索商品`
      });
    } else { 
      wx.navigateTo({
        url: `../fxShopList/fxShopList?val=${this.data.val}&title=搜索分销商品`
      })
    }
  },
  openHistorySearch: function(res) {
    this.setData({
      searchRecord: wx.getStorageSync('searchRecord') || [], //若无储存则为空
    })
  },
  search(e) { //点击搜素
    this.setStorage()
    if (this.data.val.length > 0) {
      if (this.data.isFenXiao != 'true') {
        wx.redirectTo({
          url: `../ShopList/ShopList?val=${this.data.val}&title=搜索商品`
        })
      } else {
        wx.navigateTo({
          url: `../fxShopList/fxShopList?val=${this.data.val}&title=搜索分销商品`
        })
       }

    } else {
      wx.navigateBack({
        delta: 1
      })
    }
  },
  setStorage() { //缓存处理
    var that = this
    var inputVal = this.data.val
    var searchRecord = this.data.searchRecord
    if (inputVal == '') {
      //输入为空时的处理
    } else {
      //将搜索值放入历史记录中,只能放前五条
      if (searchRecord.length < 5) {
        searchRecord.unshift({
          value: inputVal,
          id: searchRecord.length
        })
      } else {
        searchRecord.pop() //删掉旧的时间最早的第一条
        searchRecord.unshift({
          value: inputVal,
          id: searchRecord.length
        })
      }
      //将历史记录数组整体储存到缓存中
      wx.setStorageSync('searchRecord', searchRecord)
    }
  },
  historyDelFn: function() {
    wx.clearStorageSync('searhRecord')
    this.setData({
      searchRecord: []
    })
  },
  getHotWords() {
    util.API('shop/v1.shop/hot_goods').then(
      res => {
        let {
          data,
          code
        } = res
        if (code === 200) {
          this.setData({
            renmenList: data,
            hotList: data.splice(0, 5)
          })
        }
      }
    )
  },
  onLoad: function(options) {
    this.setData({
      isFenXiao: options.isFenXiao
    })
    this.getHotWords()
    this.openHistorySearch()
  }
}))